<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class User extends MY_Controller
{
	private $_id = false;
	
	public function __construct()
	{
		parent::__construct();
		$this->page_auth->secure_page(['registrar','encoder']);
		$this->view_data['system_message'] = $this->_msg();
	}
	
	public function index()
	{
		
	}
	
	public function addstudent()
	{
		$this->load->model(['M_levels','M_enrollment']);
		$this->view_data['grade_levels'] = $this->M_levels->get_all_levels_array();

		$year[''] = '-- Choose a Year --';
		foreach(range(1990,date('Y')-2) as $v)
		{
			$year[$v] = $v;
		}

		$this->view_data['year'] = $year;

		if($this->input->post('add_new_student'))
		{
			$post = $this->input->post();
			$result = $this->M_enrollment->enroll($post);

			if($result->stat)
			{
				$this->_msg('s',$result->message,'user/addstudent');
			}else{
				$this->_msg('e',$result->message,'user/addstudent');
			}
		}
	}
	
	public function parentlogin()
	{
		$this->load->model(array('M_users','M_enrollees'));

		if($this->input->post('create_parent_login'))
		{
			$this->form_validation->set_rules('parent_username', 'User Email', 'required|is_unique[users.username]|email');
			$this->form_validation->set_rules('parent_password', 'Password', 'required');
			$this->form_validation->set_rules('parent_cpassword', 'Confirm Password', 'required|matches[parent_password]');
			$this->form_validation->set_rules('children[]', 'Children', 'required');
			$this->form_validation->set_error_delimiters('<span class="error-small">', '</span>');
			if($this->form_validation->run() == false)
			{
				$this->view_data['system_message'] = $this->_msg('e','Some data contains errors.');
			}else{
				$res = $this->M_users->create_parent_login($this->input->post());
				if($res)
				{
					$this->M_enrollees->_insert_to_username_password_table($res['_id'],$res['_password'],'guardian');
					// vd($res);
					// $this->_email_parent_password($res);
					sleep(3);
					
					$this->_msg('s','Successfully generated student parent login.','user/parentlogin');
				}else{
					$this->_msg('e','Unable to generate student parent login.','user/parentlogin');
				}
			}
			// pd($this->input->post());
		}

		$total = $this->M_users->count_parent_login();

		$this->_init_pagnate_config();
		$this->load->library('pagination');
		
		$this->pagnate_config['base_url'] = base_url().'user/parentlogin/';
		$this->pagnate_config['per_page'] = 12;
		$this->pagnate_config['uri_segment'] = 3;
		$this->pagnate_config['total_rows'] = $total;
		$this->pagnate_config['suffix'] = '#parent-login';
		$this->pagination->initialize($this->pagnate_config);
		$page = ($this->uri->segment(3)) ? $this->uri->segment(3) : 0;
		if($this->input->post('search'))
		{
			$parent = $this->input->post('parent_search_data',TRUE);
			$f_parent = strpos($parent,'-') > 0 ? explode('-',$parent) : FALSE;
			if($f_parent){
				$this->view_data['login'] = $this->M_users->get_parent_login(FALSE,FALSE,$f_parent[0]);
				$this->view_data['links'] = NULL;
			}else{
				redirect('user/parentlogin#parent-login');
			}
		}else{
			$this->view_data['login'] = 	$this->M_users->get_parent_login($this->pagnate_config['per_page'],$page);
			$this->view_data['links'] = $this->pagination->_create_links(); // custom create links
		}
		
	}
	
	/**
	 * Edit Parent Login
	 * Update Username and password
	 */
	public function edit_parent_login($hash = false)
	{
		$x = $this->hs->decrypt($hash);

		if($x){
			$this->load->model('M_users');
			$this->_id = $x[0];

			$x = $this->M_users->get_all_users($x[0]);

			$this->view_data['parent'] = $parent = $x[0];
			if($x === false){ show_404(); }
			
			$this->load->library('token');
			$this->token->set_token();
			$this->view_data['form_token'] = $this->token->get_token();

			if($this->input->post('update_parent_login')){

				$token = $this->input->post('form_token');
				if($this->token->validate_token($token))
				{
					if(!$this->input->post('inc_username') && !$this->input->post('inc_password')){
						$this->_msg('e','No selected action.', current_url());
					}

					$data = false;
					if($this->input->post('inc_username')){

						$this->form_validation->set_rules('parent_username', 'User Email', 'required|email|callback_username_check');

						if($parent->username !== $this->input->post('parent_username')){
							$data['username'] = $this->input->post('parent_username');
						}
					}
					if($this->input->post('inc_password')){

						$this->form_validation->set_rules('parent_password', 'Password', 'required');
						$this->form_validation->set_rules('parent_cpassword', 'Confirm Password', 'required|matches[parent_password]');
					}

					if($this->form_validation->run() == false)
					{
						$this->view_data['system_message'] = $this->_msg('e',validation_errors());
					}else{
						
						/* SAVE DATA HERE */
						$rs = $this->M_users->update_parent_login($this->input->post(), $this->_id);
						if($rs){
							$this->_msg('s','Login details successfully updated.', current_url());
						}else{
							$this->_msg('e','Login details failed to be updated.  Please try again.', current_url());
						}
					}
				}else{ show_404(); }
			}
		}
		else{
			show_404();
		}
	}
	
	/**
	 * Add Student to Parent Login
	 * @hash string user id
	 */
	public function add_student_to_parent_login($hash = false)
	{
		$x = $this->hs->decrypt($hash);
		$this->view_data['system_message'] = $this->_msg();
		if($x){
			$this->load->model('M_users');
			$this->_id = $x[0];

			$parent = $this->M_users->get_parent_login(0,0, $x[0]);
			if($parent === false){ show_404(); }
			$this->view_data['parent'] = (object)$parent[0];
			$this->view_data['user_id'] = $x[0];
			// vd($parent[0]);
			
			$this->load->library('token');
			$this->token->set_token();
			$this->view_data['form_token'] = $this->token->get_token();

			if($this->input->post('update_parent_login')){
				if($this->input->post('children')){

					$res = $this->M_users->add_student_to_parent_login($x[0], $this->input->post('children'));
					if($res)
					{	
						$this->_msg('s','Successfully added student  to parent login.',current_url());
					}else{
						$this->_msg('e','Unable to generate student parent login.',current_url());
					}
				}else{
					$this->_msg('e','No Student selected', current_url());
				}
			}
		}
		else{
			show_404();
		}
	}
	
	public function allparentlogin()
	{
		$this->load->model('M_users');
		$this->load->model('M_search');
		
		//$type = 'mothername';
		
		$siblings = $this->M_search->get_siblings_all();
		
		$created = 0;
		
		foreach($siblings as $key => $val):
			foreach($val as $k => $v):
				foreach($v as $fathername => $values):
					if($values['children']):
						foreach($values['children'] as $sk => $sv):
							$enrollment_ids[md5($values['mother'])][] = $sk;
						endforeach;
							$e_ids = array_map('intval',$enrollment_ids[md5($values['mother'])]);
							$created += $this->_generate_all_parent_login(__link_array($e_ids));
					endif;
				endforeach;
			endforeach;
		endforeach;
		
		$this->_msg('s','Successfully generated '.$created.' parent login. Please check for completion, else press again the one click parents log in generation button.','user/parentlogin#parent-login');
		
	}
	
	public function _generate_all_parent_login($hash = '')
	{
		$x = $this->hs->decrypt($hash);

		if($x)
		{
			$this->load->model('M_users');
			$result = $this->M_users->resend_parentlogin($x);
			$this->_email_parent_password($result->userdata);
			
			if($result->status == TRUE)
			{
				return 1;
			}else{
				return 0;
			}
		//if direct link access with no hash
		}/*else{
			show_error('Unable to process request.',404);		
		}*/
	}
	
	public function delete_student_from_parent_login($hash = '')
	{
		$x = $this->hs->decrypt($hash);

		if(IS_AJAX && $x)
		{
			$this->load->model('M_users');
			$res = $this->M_users->delete_student_from_login($x[0]);

			if($res == TRUE)
			{
				$result = 1;
			}else{
				$result = 0;
			}

			header('Content-Type: application/json');
			echo json_encode($result);
			exit();

		//if manual http request
		}else if($x)
		{
			$this->load->model('M_users');
			if($this->M_users->delete_student_from_login($x[0]))
			{
				$this->_msg('s','Student is now deleted from parent login.','user/parentlogin#parent-login');
			}else{
				$this->_msg('e','Unable to delete student from parent login.','user/parentlogin#parent-login');
			}
		}else{
			show_404();
		}
	}
	
	public function delete_login($hash = '')
	{
		$x = $this->hs->decrypt($hash);

		if(IS_AJAX && $x)
		{
			$this->load->model('M_users');
			$res = $this->M_users->delete_login($x[0]);

			if($res == TRUE)
			{
				$result = 1;
			}else{
				$result = 0;
			}

			header('Content-Type: application/json');
			echo json_encode($result);
			exit();

		//if manual http request
		}else if($x)
		{
			$this->load->model('M_users');
			if($this->M_users->delete_login($x[0]))
			{
				$this->_msg('s','Login now deleted.','user/parentlogin#parent-login');
			}else{
				$this->_msg('e','Unable to delete parent login.','user/parentlogin#parent-login');
			}
		}else{
			show_404();
		}
	}
	
	public function auth($hash = '',$type='')
	{
		$x = $this->hs->decrypt($hash);

		if($x && in_array(strtolower($type),['enable','disable']))
		{
			$this->load->model('M_users');
			if($this->M_users->on_off_login($x[0],$type))
			{
				$message = $type == 'enable' ? 'Successfully enabled login.' : 'Login now disabled.';
				$this->_msg('s',$message,'user/parentlogin#parent-login');
			}else{
				$message = $type == 'enable' ? 'Error unable to enable parent login.' : 'Error. Unable to disable parent login.';
				$this->_msg('e',$message,'user/parentlogin#parent-login');
			}
		}else{
			show_404();
		}		
	}
	
	public function resend($hash = '')
	{
		$x = $this->hs->decrypt($hash);

		if($x)
		{
			$this->load->model('M_users');
			$result = $this->M_users->resend_parentlogin($x);
			$this->_email_parent_password($result->user);
			
			if($result->status == TRUE)
			{
				$this->_msg('s','Successfully resend Username and Password for parent to email.','user/parentlogin#parent-login');
			}else{
				$this->_msg('e','Unable to resend Username and Password for parent.','user/parentlogin#parent-login');
			}
		//if direct link access with no hash
		}else{
			show_error('Unable to process request.',404);		
		}
	}
	
	public function generate_parent_login($hash = '')
	{
		$x = $this->hs->decrypt($hash);

		//if ajax request
		if(IS_AJAX && $x)
		{
			$this->load->model('M_users');
			$res = $this->M_users->autogenerate_parentlogin($x);

			if($res->status == TRUE)
			{
				$this->_email_parent_password($res->user);
				$result = 1;
			}else{
				$result = 0;
			}

			header('Content-Type: application/json');
			echo json_encode($result);
			exit();

		//if manual http request
		}
			elseif($x)
		{
			$this->load->model('M_users');
			$result = $this->M_users->autogenerate_parentlogin($x);
			$this->_email_parent_password($result->userdata);
			
			if($result->status == TRUE)
			{
				$this->_msg('s','Successfully generated Username and Password for parent and sent to email.','search/siblings');
			}else{
				$this->_msg('e','Unable to generate Username and Password for parent.','search/siblings');
			}
		//if direct link access with no hash
		}else{
			show_error('Unable to process request.',404);		
		}
	}
	
	private function _email_parent_password($logincred)
	{
		$school_name = ucwords($this->school_name);
		$school_name_title = $this->_accronymizer($this->school_name).'@DONOTREPLY.com';
		$student_page_link = $this->student_link;
		
		if($this->school_tag_name == FALSE)
		{
			$tagname = 'part of '.$school_name;
		}else{
			$tagname = 'a '.strtoupper($this->school_tag_name);
		}

		$data['school_name'] = $school_name;
		$data['acc'] = $school_name_title;
		$data['link'] = $student_page_link;
		$data['tagname'] = $tagname;
		$data['username'] = $logincred['_username'];
		$data['password'] = $logincred['_password'];
		
		$message = $this->load->view('email_templates/email_parent_login',$data,TRUE);
		
		$this->load->library('email');
		$this->email->initialize(array( 
		   'mailtype' => 'html', 
		));

		foreach($logincred['_useremails'] as $_mail)
		{
			$this->email->from($school_name_title,$school_name);
			$this->email->to($_mail->email);
			$this->email->subject('New Account Login Details.');
			$this->email->message($message);
			$this->email->send();		
		}

		/* ADDED | Since User name became an EMAIL - send also to the useremail  | Sylver - 8/14/2014*/
		$this->email->from($school_name_title,$school_name);
		$this->email->to($data['username']);
		$this->email->subject('New Account Login Details.');
		$this->email->message($message);
		$this->email->send();	
	}
	
	public function email_me()
	{	/*
		$school_name = ucwords($this->school_name);
		$school_name_title = $this->_accronymizer($this->school_name).'@westfields-is.com';
		$student_page_link = $this->student_link;
		
		if($this->school_tag_name == FALSE)
		{
			$tagname = 'part of '.$school_name;
		}else{
			$tagname = 'a '.strtoupper($this->school_tag_name);
		}

		$data['school_name'] = $school_name;
		$data['acc'] = $school_name_title;
		$data['link'] = $student_page_link;
		$data['tagname'] = $tagname;
		//$data['username'] = $logincred['_username'];
		//$data['password'] = $logincred['_password'];
		*/
		//$message = $this->load->view('email_templates/email_parent_login',$data,TRUE);
		$message = 'test';
		
		$this->load->library('email');
		$this->email->initialize(array( 
		   'mailtype' => 'html', 
		));

		/* ADDED | Since User name became an EMAIL - send also to the useremail  | Sylver - 8/14/2014*/
		$this->email->from('hay.an2ny@gmail.com');
		$this->email->to('hay.an2ny@gmail.com');
		$this->email->subject('New Account Login Details.');
		$this->email->message($message);
		$this->email->send();	
	}
}
?>